package com.cby.android.library.ext

import com.cby.android.olive.CbyOliveTools
import com.cby.android.olive.ext.showToast
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.catch
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * @description: FlowExt
 *
 * @author ChenBaoyang
 * @date 2021/12/3 17:14
 */

fun <T> Flow<T>.commonCatch(action: suspend FlowCollector<T>.(cause: Throwable) -> Unit): Flow<T> {

    return this.catch {
        if (it is UnknownHostException || it is SocketTimeoutException) {
            CbyOliveTools.application?.showToast("发生网络错误，请稍后重试")
        } else {
            CbyOliveTools.application?.showToast("请求失败，请重试")
        }
        action(it)
    }

}